package com.example.dicegame.controller;

import com.example.dicegame.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/api/dice")
public class DiceController {

    @Autowired
    private RedisService redisService;

    private Random random = new Random();

    @PostMapping("/roll")
    public Map<String, Object> rollDice(@RequestParam(defaultValue = "1") int count) {
        Map<String, Object> result = new HashMap<>();

        if (count < 1 || count > 6) {
            result.put("success", false);
            result.put("message", "骰子数量必须在1-6之间");
            return result;
        }

        // 生成骰子结果
        int[] diceResults = new int[count];
        int total = 0;

        for (int i = 0; i < count; i++) {
            diceResults[i] = random.nextInt(6) + 1;  // 生成1-6的随机数
            total += diceResults[i];
        }

        // ========== 使用 RedisService 进行数据存储 ==========

        // 1. String - 更新总摇骰子次数
        redisService.increment("dice:total_roll_count");

        // 2. Set - 记录出现的总点数（自动去重）
        redisService.addToSet("dice:all_points", total);

        // 3. 为每个骰子值也记录到 Set
        for (int diceValue : diceResults) {
            redisService.addToSet("dice:individual_values", diceValue);
        }

        // 4. List - 保存历史记录（使用 RedisService）
        String historyKey = "dice_roll_history";
        String record = System.currentTimeMillis() + ":" + total + ":" + Arrays.toString(diceResults);

        // 使用 RedisService 保存历史记录
        redisService.leftPush(historyKey, record);

        // 限制历史记录数量
        if (redisService.listSize(historyKey) > 10) {
            redisService.listTrim(historyKey, 0, 9);
        }

        result.put("success", true);
        result.put("dice", diceResults);
        result.put("total", total);
        result.put("timestamp", System.currentTimeMillis());

        return result;
    }


    @GetMapping("/history")
    public Map<String, Object> getHistory() {
        Map<String, Object> result = new HashMap<>();
        try {
            result.put("success", true);
            // 使用 RedisService 获取历史记录
            List<Object> historyList = redisService.range("dice_roll_history", 0, 9);
            result.put("history", historyList != null ? historyList : new ArrayList<>());
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取历史记录失败: " + e.getMessage());
        }
        return result;
    }

    // ==================== String 操作示例 ====================

    /**
     * 统计总摇骰子次数 - 使用 String 作为计数器
     */
    @PostMapping("/stats/count")
    public Map<String, Object> incrementRollCount() {
        Map<String, Object> result = new HashMap<>();

        Long totalCount = redisService.increment("dice:total_roll_count");

        result.put("success", true);
        result.put("totalRollCount", totalCount);
        result.put("message", "摇骰子总次数已更新");

        return result;
    }

    /**
     * 获取统计信息 - 使用 String
     */
    @GetMapping("/stats/count")
    public Map<String, Object> getRollCount() {
        Map<String, Object> result = new HashMap<>();

        String countStr = redisService.getString("dice:total_roll_count");
        Long totalCount = countStr != null ? Long.parseLong(countStr) : 0L;

        result.put("success", true);
        result.put("totalRollCount", totalCount);

        return result;
    }

    // ==================== Hash 操作示例 ====================

    /**
     * 记录用户游戏数据 - 使用 Hash 存储用户信息
     */
    @PostMapping("/user/stats")
    public Map<String, Object> updateUserStats(@RequestParam String username) {
        Map<String, Object> result = new HashMap<>();

        String userKey = "user:stats:" + username;

        // 使用 Hash 存储用户的多维度数据
        redisService.setHash(userKey, "lastPlayTime", System.currentTimeMillis());

        // 获取用户游戏次数
        String playCountKey = "user:play_count:" + username;
        Long userPlayCount = redisService.increment(playCountKey);

        result.put("success", true);
        result.put("username", username);
        result.put("userPlayCount", userPlayCount);
        result.put("message", "用户数据已更新");

        return result;
    }

    /**
     * 获取用户统计信息 - 使用 Hash
     */
    @GetMapping("/user/stats/{username}")
    public Map<String, Object> getUserStats(@PathVariable String username) {
        Map<String, Object> result = new HashMap<>();

        String userKey = "user:stats:" + username;
        String playCountKey = "user:play_count:" + username;

        // 从 Hash 获取数据
        Object lastPlayTime = redisService.getHash(userKey, "lastPlayTime");
        String playCountStr = redisService.getString(playCountKey);

        result.put("success", true);
        result.put("username", username);
        result.put("lastPlayTime", lastPlayTime);
        result.put("playCount", playCountStr != null ? Long.parseLong(playCountStr) : 0);

        return result;
    }

    // ==================== Set 操作示例 ====================

    /**
     * 记录出现的点数 - 使用 Set 存储不重复的点数
     */
    @PostMapping("/stats/points")
    public Map<String, Object> recordPoints(@RequestParam int points) {
        Map<String, Object> result = new HashMap<>();

        // 使用 Set 记录所有出现过的总点数（自动去重）
        redisService.addToSet("dice:all_points", points);

        result.put("success", true);
        result.put("points", points);
        result.put("message", "点数已记录到集合");

        return result;
    }

    /**
     * 获取所有出现过的点数 - 使用 Set
     */
    @GetMapping("/stats/points")
    public Map<String, Object> getAllPoints() {
        Map<String, Object> result = new HashMap<>();

        // 获取 Set 中的所有元素
        Set<Object> pointsSet = (Set<Object>) redisService.getSetAll("dice:all_points");
        Long setSize = redisService.getSetSize("dice:all_points");

        result.put("success", true);
        result.put("allPoints", pointsSet != null ? pointsSet : new HashSet<>());
        result.put("uniquePointsCount", setSize);

        return result;
    }

    /**
     * 检查点数是否出现过 - 使用 Set
     */
    @GetMapping("/stats/points/{points}/exists")
    public Map<String, Object> checkPointsExists(@PathVariable int points) {
        Map<String, Object> result = new HashMap<>();

        Boolean exists = redisService.isMembersOfSet("dice:all_points", points);

        result.put("success", true);
        result.put("points", points);
        result.put("exists", exists);

        return result;
    }

    @GetMapping("/health")
    public Map<String, Object> healthCheck() {
        Map<String, Object> result = new HashMap<>();
        result.put("status", "UP");
        result.put("service", "dice-game-backend");
        result.put("timestamp", System.currentTimeMillis());
        return result;
    }
}